﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BW.Mes.WinForms.BasicData;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static BW.Mes.WinForms.BasicData.SupplierForm;
using BW.Mes.WinForms;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddSupplierForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        
        public AddSupplierForm()
        {
            InitializeComponent();
            this.Load += AddSupplierForm_AutoGenSupplierCode;
            this.textEditMsg.EditValueChanged += textEditMsg_EditValueChanged;
            this.textEditMsg.Properties.MaxLength = 50;
            labelControlCount.Text = $"{textEditMsg.Text.Length}/50";
        }
        
        private async void AddSupplierForm_AutoGenSupplierCode(object sender, EventArgs e)
        {
            // 自动生成供应商编号
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"GYL{today}";
            int maxSerial = 0;
            try
            {
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Supplier/GetSupplier");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var jsonObject = JObject.Parse(json);
                    var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                    if (listToken != null)
                    {
                        var suppliers = JsonConvert.DeserializeObject<List<SupplierModel>>(listToken.ToString());
                        if (suppliers != null)
                        {
                            foreach (var item in suppliers)
                            {
                                string code = item.SupplierCode;
                                if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                {
                                    string serialStr = code.Substring(prefix.Length);
                                    if (int.TryParse(serialStr, out int serial))
                                    {
                                        if (serial > maxSerial) maxSerial = serial;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textEditCode.Text = newCode;
            textEditCode.Properties.ReadOnly = true;
        }
        
        private async void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(textEditCode.Text))
                {
                    XtraMessageBox.Show("供应商编号不能为空！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEditCode.Focus();
                    return;
                }
                if (string.IsNullOrWhiteSpace(textEditName.Text))
                {
                    XtraMessageBox.Show("供应商名称不能为空！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEditName.Focus();
                    return;
                }
                string phone = textEditPhone.Text.Trim();
                if (phone.Length != 11 || !System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{11}$"))
                {
                    XtraMessageBox.Show("电话必须为11位数字！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                var model = new
                {
                    supplierCode = textEditCode.Text.Trim(),
                    supplierName = textEditName.Text.Trim(),
                    abbreviation = textEditAbbreviation.Text?.Trim(),
                    suppType = comboBoxEditSuppType.Text?.Trim(),
                    suppLeave = comboBoxEditSuppLeave.Text?.Trim(),
                    phone = textEditPhone.Text?.Trim(),
                    suppHangye = comboBoxEditSuppHangye.Text?.Trim(),
                    address = textEditAddress.Text?.Trim(),
                    uscc = textEditUSCC.Text?.Trim(),
                    status = comboBoxEditStatus.Text?.Trim(),
                    supplierMsg = textEditMsg.Text?.Trim(),
                    createdBy = "admin",
                    createdAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
                };
                string jsonData = JsonConvert.SerializeObject(model);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync($"{_apiBaseUrl}/T2/Supplier/AddSupplier", content);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && ( (apiResult.code != null && apiResult.code.ToString() == "200") || (apiResult.message != null && apiResult.message.Contains("成功")) ))
                        {
                            XtraMessageBox.Show("新增成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            string errorMessage = apiResult?.message ?? "新增失败，未知错误";
                            XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (JsonException)
                    {
                        XtraMessageBox.Show("新增成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch { }
                    XtraMessageBox.Show($"新增失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"新增过程中发生错误：{ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddSupplierForm_Load(object sender, EventArgs e)
        {

        }

        private void textEditMsg_EditValueChanged(object sender, EventArgs e)
        {
            var text = textEditMsg.Text;
            if (text.Length > 50)
            {
                textEditMsg.Text = text.Substring(0, 50);
                textEditMsg.SelectionStart = 50;
            }
            labelControlCount.Text = $"{textEditMsg.Text.Length}/50";
        }
    }
}